﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Net;
using System.Net.Http;
using System.Web;
using System.Web.Http;
using FimetContoDeposito.BLL.Facades;
using FimetContoDeposito.BLL.ResultSets;
using GrayParrot.Core;
using GrayParrot.Core.Json;
using GrayParrot.Web.Controls;
using GrayParrot.Web.Formly;
using Newtonsoft.Json;
using Newtonsoft.Json.Linq;
using Test.DAL;
using WebTest.Metadata;

namespace WebTest.Controllers
{
    public class CustomersController : GridCrudController<JObject, DTParameters>
    {
        #region Load Fields...
        [HttpGet]
        public string LoadFields()
        {
            string retValue = null;

            var m_fields = FormlyHelper.ToFormly<CustomerMetadata>(typeof(CustomerMetadata));

            JsonSerializerSettings settings = new JsonSerializerSettings();
            settings.ContractResolver = new NullToEmptyListResolver();
            settings.Converters = new List<JsonConverter> { new Newtonsoft.Json.Converters.StringEnumConverter { CamelCaseText = false } };
            settings.Formatting = Formatting.Indented;
            settings.NullValueHandling = NullValueHandling.Ignore;

            retValue = JsonConvert.SerializeObject(m_fields, settings);

            return retValue;
        }

        [HttpGet]
        public string[] LoadFields(string id)
        {
            string[] retValue = new string[2] { string.Empty, string.Empty };

            Customer obj = null;
            using (CustomersFacade m_dc = CustomersFacade.Create())
            {
                ReturnValue<Customer> m_objs = m_dc.Get(id);
                if (m_objs.HasValue)
                {
                    obj = m_objs.Value;
                }


                m_dc.Repo.Add(m_objs.Value);
            }

            if (obj != null)
            {
                var m_fields = FormlyHelper.ToFormly<CustomerMetadata>(typeof(CustomerMetadata));

                JsonSerializerSettings settings = new JsonSerializerSettings();
                settings.ContractResolver = new NullToEmptyListResolver();
                settings.Converters = new List<JsonConverter> { 
                    new Newtonsoft.Json.Converters.StringEnumConverter { CamelCaseText = false }
                };

                settings.Formatting = Formatting.Indented;
                settings.NullValueHandling = NullValueHandling.Ignore;

                retValue[0] = JsonConvert.SerializeObject(m_fields, settings);

                retValue[1] = JsonConvert.SerializeObject(obj);
            }
            else
            {
            }

            //
            return retValue;
        }  
        #endregion

        public override System.Net.Http.HttpResponseMessage Add(JObject data)
        {
            System.Net.Http.HttpResponseMessage retValue = new HttpResponseMessage(HttpStatusCode.BadRequest);




            return retValue;
        }

        public override System.Net.Http.HttpResponseMessage Edit(JObject data)
        {
            throw new NotImplementedException();
        }

        public override System.Net.Http.HttpResponseMessage Delete(int id)
        {
            throw new NotImplementedException();
        }

        public override System.Net.Http.HttpResponseMessage Load(DTParameters data)
        {
            System.Net.Http.HttpResponseMessage retValue = new HttpResponseMessage(HttpStatusCode.BadRequest);

            using (CustomersFacade m_dc = CustomersFacade.Create())
            {
                ReturnValue<IQueryable<Customer>> m_objs = m_dc.GetAll();

                DTResult<Customer> result = DTResult<Customer>.Empty("Nessun elemento trovato");
                if (m_objs.HasValue)
                {
                    CustomersResultSet m_rs = new CustomersResultSet(data, m_objs.Value);
                    result = m_rs.GetResult();
                }
                else
                {
                    if (m_objs.HasError)
                    {
                        result.Message.MessageType = MessageTypes.Error;
                        result.Message.Message = m_objs.Error.Message;
                    }
                }

                retValue = Request.CreateResponse(HttpStatusCode.OK, result);
            }

            return retValue;
        }

        [HttpPost]
        public override System.Net.Http.HttpResponseMessage Delete(JObject data)
        {
            System.Net.Http.HttpResponseMessage retValue = new HttpResponseMessage(HttpStatusCode.BadRequest);


            return retValue;
        }

        //[HttpGet]
        //public List<NameValue<string, string>> LoadCompanies()
        // {"query":{"page":2,"_type":"query:append"},"pageLimit":30}:
        [HttpPost]
        public SelectFilterResult<IEnumerable<NameValue<string, string>>> LoadCompanies(SelectFilterParams data) //JObject data)
        {
            //dynamic json = data;
            //int m_skip = 1; // json.query.page;
            //int m_take = int.Parse(json.pageLimit.ToString());

            SelectFilterResult<IEnumerable<NameValue<string, string>>> retValue = null;

            using (CustomersFacade m_cf = CustomersFacade.Create())
            {
                var objs = m_cf.GetCompanies();

                if (objs.HasValue)
                {
                    if (objs.Value.Any())
                    {
                        retValue = new SelectFilterResult<IEnumerable<NameValue<string, string>>>();
                        IEnumerable<NameValue<string, string>> objs2 = null;
                        if ((data == null) || (string.IsNullOrWhiteSpace(data.SearchTerm)))
                        {
                            objs2 = objs.Value.Select(x => new NameValue<string, string>() { name = x, value = x });
                        }
                        else
                        {
                            objs2 = objs.Value.Select(x => new NameValue<string, string>() { name = x, value = x }).Where(x=>x.name.ToLower().Contains(data.SearchTerm.ToLower()));
                        }

                        if ((data != null) && (data.PageNumber != 0) && (data.PageSize != 0))
                        {
                            retValue.Results = objs2.Skip((data.PageNumber - 1) * data.PageSize).Take(data.PageSize).ToList();
                        }
                        else
                        {
                            retValue.Results = objs2.ToList();
                        }


                        retValue.Total = objs2.Count();
                    }
                }
            }

            return retValue;
        }
    }
}